package com.xtianzhuang.www.study2019.practice.leetcode.study.set;

import java.util.HashSet;
import java.util.Set;

public class Solution {
	public static void main(String[] args) {
		isHappy(19);
	}

	/**
	 * 一个“快乐数”定义为：对于一个正整数，每一次将该数替换为它每个位置上的数字的平方和，
	 * 然后重复这个过程直到这个数变为 1，也可能是无限循环但始终变不到 1。如果可以变为 
	 * 1，那么这个数就是快乐数。
	 * @param n
	 * @return
	 */
	public static boolean isHappy(int n) {
		int tmp;
		Set<Integer> set = new HashSet<>();

		while (n != 1) {

			tmp = cal(n);
			if (set.contains(tmp)) {
				return false;
			}
			set.add(tmp);
			n = tmp;
		}
		return true;
	}

	public static int cal(int n) {
		int sum = 0;
		while (n > 0) {
			int index = n % 10;
			n = n / 10;
			sum += index * index;
			// System.out.print(index + "²");
			if (n > 0) {
				// System.out.print("+");
			}
		}
		// System.out.println("=" + sum + "\n");
		return sum;
	}

	/**
	 * 链表的思路，寻找最短闭环
	 * @param n
	 * @return
	 */
	public boolean isHappy2(int n) {
		int fast = n;
		int slow = n;
		do {
			slow = squareSum(slow);
			fast = squareSum(fast);
			fast = squareSum(fast);
		} while (slow != fast);
		if (fast == 1)
			return true;
		else
			return false;
	}

	private int squareSum(int m) {
		int squaresum = 0;
		while (m != 0) {
			squaresum += (m % 10) * (m % 10);
			m /= 10;
		}
		return squaresum;
	}
}
